/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fileuploaddownload;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author tomasz
 */
@Controller
public class FileDownload {
    
    private dao.File file;
    
    @Autowired
    public void setFile(dao.File file){
        this.file = file;
    }
    
    
    @RequestMapping(value = "/download.htm/{idfile}", method = RequestMethod.GET)
    public @ResponseBody byte[] getInvoice(@PathVariable("idfile") Integer idfile, HttpServletResponse response, HttpServletRequest request) throws IOException {


        model.File fi = this.file.findFileId(idfile);
        
        ServletContext context = request.getSession().getServletContext();
        String realPath = context.getRealPath("/");
        String destinationDir = realPath + "\\temp\\";
        String fileName = destinationDir+fi.getNameHash();;
        File file = new File(fileName);

        //String f = "1065.jpg";
        String f = fi.getNameHash();
        
        String fileType = f.substring(f.indexOf(".") + 1, f.length());
        
        if (fileType.trim().equalsIgnoreCase("txt")) {
            response.setContentType("text/plain");
        } else if (fileType.trim().equalsIgnoreCase("doc")) {
            response.setContentType("application/msword");
        } else if (fileType.trim().equalsIgnoreCase("xls")) {
            response.setContentType("application/vnd.ms-excel");
        } else if (fileType.trim().equalsIgnoreCase("pdf")) {
            response.setContentType("application/pdf");
        } else if (fileType.trim().equalsIgnoreCase("ppt")) {
            response.setContentType("application/ppt");
        }  else if (fileType.trim().equalsIgnoreCase("jpg")) {
           response.setContentType("image/jpeg");
        }else {
            response.setContentType("application/octet-stream");
        }
    
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setContentLength((int) file.length());
        return FileUtils.readFileToByteArray(file);
        
    }

    
    
}
